/*
 * @Author: Xiao Xiang Lun
 * @LastEditors: Xiao Xiang Lun
 * @Date: 2021-06-22 10:23:27
 * @LastEditTime: 2021-06-22 10:33:54
 * @FilePath: /intelligence-application/src/utils/ImgToBase64.js
 * @Environment: Win 10 node.js V 12.13.0
 * @Description:
 */
interface GetImgToBase64 {
  (url: string): Promise<string>;
}

interface ImgOnLoad {
  (): void;
}

interface ImgOnError {
  (err: string | Event): void;
}

export default function getImgToBase64(url: string): Promise<string> { // 将图片转换为Base64
  return new Promise((resolve) => {
    let canvas: HTMLCanvasElement | null = document.createElement('canvas');
    let ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
    let img: HTMLImageElement = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = function() {
      if (canvas && ctx) {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL: string = canvas.toDataURL('image/png');
        canvas = null;
        resolve(dataURL);
      }
    } as ImgOnLoad;
    img.onerror = function(err) {
      console.log('οnerrοr', err);
      img.onerror = null;
      resolve('err');
    } as ImgOnError;
    img.src = url;
  });
}
